package com.zkthink.ceres.applet.authority.service.impl;

import com.zkthink.ceres.applet.authority.domain.entity.AppletMember;
import com.zkthink.base.R;
import com.zkthink.ceres.applet.authority.dto.CommonAppletLoginDTO;
import com.zkthink.ceres.applet.authority.dto.RegDTO;
import com.zkthink.ceres.applet.authority.service.AppletAuthService;
import com.zkthink.ceres.applet.authority.service.AppletMemberService;
import com.zkthink.ceres.common.utils.ValidatorUtil;
import com.zkthink.ceres.member.event.LoginEvent;
import com.zkthink.database.mybatis.conditions.query.QueryWrap;
import com.zkthink.jwt.TokenUtil;
import com.zkthink.jwt.model.AuthInfo;
import com.zkthink.jwt.model.JwtUserInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

/**
 * Created by kellen on 2020/5/3.
 */
@Service
@AllArgsConstructor
@Slf4j
public class AppletAuthServiceImpl implements AppletAuthService {
    @Autowired
    private AppletMemberService appletMemberService;

    private TokenUtil tokenUtil;

    private ApplicationEventPublisher publisher;

    private final PasswordEncoder passwordEncoder;

    

    @Override
    @Transactional
    public R<AuthInfo> login(CommonAppletLoginDTO appLoginDTO) {
        QueryWrap<AppletMember> queryWrap = new QueryWrap<>();
        queryWrap.eq("phone",appLoginDTO.getAccount());
        AppletMember member = appletMemberService.getOne(queryWrap);
        if (null == member) {
            return R.validFail("用户名或密码错误");
        }
        if (member.getStatus()==1) {
            return R.fail("您已被禁用");
        }


        if (StringUtils.isNotBlank(appLoginDTO.getPassWord())) {
            //密码校验
            boolean isMatch = passwordEncoder.matches(appLoginDTO.getPassWord(), member.getPassword());
            System.out.println(isMatch);
            if (!isMatch) {
                return R.fail("用户名或密码错误");
            }
        }


        member.setLoginNum(member.getLoginNum() + 1);
        member.setLoginTime(new Date());
        appletMemberService.saveOrUpdate(member);
        String nickname = "";

        JwtUserInfo userInfo = new JwtUserInfo(member.getId(), member.getAccount(),
                member.getNickname());

        userInfo.setName(nickname);

        AuthInfo authInfo = tokenUtil.createAuthInfo(userInfo, 86400L);
        authInfo.setUserType(member.getUserType());

        //发布登录事件
        publisher.publishEvent(
                LoginEvent.builder().
                        mid(member.getId()).build());


        System.out.println("登录成功");
        
        //String token = authInfo.getToken();
        //拼接测试环境的特殊token
        //authInfo.setToken( BaseContextConstants.BEARER_HEADER_PREFIX + token);
        return R.success(authInfo);
    }

    @Override
    public R register(RegDTO regDTO) {
        //注册
        AppletMember member = appletMemberService.findByAccount(regDTO.getAccount());
        if (null != member) {
            return R.fail("账号已存在");
        }
        if (!ValidatorUtil.checkPhone(regDTO.getAccount())) {
            return R.fail("请输入正确格式的手机号");
        }
        BigDecimal bigDecimal = new BigDecimal(0);
        Random random = new Random();
        member = new AppletMember();
        member.setPhone(regDTO.getAccount());
        //member.setId(UUID.randomUUID().getMostSignificantBits());
        member.setAccount(regDTO.getAccount());
        member.setNickname(regDTO.getAccount());
        member.setPassword(passwordEncoder.encode(regDTO.getPassWord()));
        member.setHeadimg("https://xsy-1308896693.cos.ap-shanghai.myqcloud.com/admin/2022/02/a0272351-b471-4d2b-ac6d-0120926fb269.png");
        member.setCoupons(bigDecimal);
        member.setBalance(bigDecimal);
        member.setReferPhone(regDTO.getReferPhone());
        member.setTichneg(bigDecimal);
        appletMemberService.save(member);

        return R.success();
    }

    @Override
    public R update(CommonAppletLoginDTO commonAppLoginDTO) {
        AppletMember member = new AppletMember();
        member.setPassword(passwordEncoder.encode(commonAppLoginDTO.getPassWord()));
        appletMemberService.getBaseMapper().update(member, new QueryWrap<AppletMember>().lambda().eq(AppletMember::getAccount, commonAppLoginDTO.getAccount()));
        return R.success();
    }

}
